import toml
from pathlib import Path
from datetime import datetime
import logger

class Const:
    CONF_PATH = Path("./conf-board.toml")

class _m:
    _root = None
    _default = None
    _updatetime = None
    _loadtime = None

    def search(path:list):
        def lookup(names:list, node):
            if len(names) > 0:
                head = names[0]
                if isinstance(node,dict) and (head in node):
                    return lookup(names[1:], node.get(head))
                return None
            return node
        val = lookup(path, _m._root)
        if val is None: return lookup(path, _m._default)
        return val

    def update(path:list, val, node) -> None:
        assert len(path) > 0
        if node is _m._root:
            _m._updatetime = datetime.now()
        for name in path[:-1]:
            next = node.get(name)
            if isinstance(next,dict):
                node = next
            else:
                node[name] = dict()
                node = node[name]
        node[path[-1]] = val

def get_int(*path) -> int:
    val = _m.search(path)
    return val if isinstance(val,int) else 0
def set_int(val:int, *path) -> int:
    assert isinstance(val,int)
    _m.update(path, val, _m._root)
    return val

def get_bool(*path) -> bool:
    val = _m.search(path)
    return val if isinstance(val,bool) else False
def set_bool(val:bool, *path) -> bool:
    assert isinstance(val,bool)
    _m.update(path, val, _m._root)
    return val

def get_str(*path) -> str:
    val = _m.search(path)
    return val if isinstance(val,str) else ""
def set_str(val:str, *path) -> str:
    assert isinstance(val,str)
    _m.update(path, val, _m._root)
    return val

def add_default(val, *path) -> None:
    assert (len(path) > 0) and (not val is None)
    _m.update(path, val, _m._default)

def _raii_by_main_use_only():
    logger.info("conf", "raii")
    if _m._updatetime != _m._loadtime:
        with open(Const.CONF_PATH, "w") as f:
            root = dict(_m._default)
            root.update(_m._root)
            toml.dump(root, f)
        logger.info("conf", "update")
    logger.info("conf", "has raii")

def _init_by_main_use_only():
    logger.info("conf", "init")
    _m._default = dict()
    try:
        with Const.CONF_PATH.open("r") as f:
            _m._root = toml.load(f)
    except:
        _m._root = dict()
    _m._loadtime = datetime.now()
    _m._updatetime = _m._loadtime
    logger.info("conf", "has init")
